#!/usr/bin/perl

use strict;
use Data::Dumper;
require LWP::UserAgent;

$| = 1;

my $ua = LWP::UserAgent->new;
$ua->timeout(10);
sub getPage {
    my $url = shift;
    my $file = shift;

    my $page = '';

    if (!-f './cache/'.$file) {
        my $response = $ua->get($url);
        
        if ($response->is_success) {
            $page = $response->decoded_content;  # or whatever
            open FF, '>./cache/'.$file;
            print FF $page;
            close FF;
        } else {
            die $response->status_line;
        }
    } else {
        open FF, './cache/'.$file;
        while (<FF>) { $page .= $_;}
        close FF;
    }
    return $page;
}

my @urls = (
    'http://us.battle.net/d3/en/class/barbarian/passive/',
    'http://us.battle.net/d3/en/class/demon-hunter/passive/',
    'http://us.battle.net/d3/en/class/monk/passive/',
    'http://us.battle.net/d3/en/class/witch-doctor/passive/',
    'http://us.battle.net/d3/en/class/wizard/passive/'
);

foreach my $url (@urls) {
    my $page = getPage($url, 'barb'.rand());

    my @T;

    while ($page =~ /<tr class="row\d">(.*?)<\/tr>/gis) {
        my $block = $1;
        my %H;
        $H{'icon'} = $1 if ($block =~ /background-image: url\('(.*?)'/);
        $H{'name'} = $1 if ($block =~ /<a href=".*?" rel="np">(.*?)<\/a>/);
        $H{'descr'} = $1 if ($block =~ /<div class="skill-description">(.*?)<\/div>/gis);
        $H{'lvl'} = $1 if ($block =~ /<h4 class="subcategory ">(\d+)<\/h4>/);
        push(@T, \%H);
        my $cmd = "wget '".$H{'icon'}."'";
        `$cmd`;
    }

    $Data::Dumper::Terse = 1;
    $Data::Dumper::Pair = " : ";
    print Dumper(\@T);
}
